package strategys;

import config.ConfigReader;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DatabaseLogStrategy implements LogStrategy {
    private String url;
    private String user;
    private String password;
    private SimpleDateFormat dateFormat;

    public DatabaseLogStrategy() {
        ConfigReader configReader = ConfigReader.getInstance();
        this.url = configReader.getDatabaseUrl();
        this.user = configReader.getDatabaseUser();
        this.password = configReader.getDatabasePassword();
        this.dateFormat = new SimpleDateFormat(configReader.getLogFormat());
    }

    @Override
    public void log(String level, String message, StackTraceElement[] stackTraceElements) {
        String timestamp = dateFormat.format(new Date());

        // 获取调用栈信息
        StackTraceElement caller = stackTraceElements[2];
        String className = caller.getClassName();
        String methodName = caller.getMethodName();
        int lineNumber = caller.getLineNumber();

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            String sql = "INSERT INTO logs (timestamp, level, class, method, line, message) VALUES (?, ?, ?, ?, ?, ?)";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, timestamp);
                stmt.setString(2, level);
                stmt.setString(3, className);
                stmt.setString(4, methodName);
                stmt.setInt(5, lineNumber);
                stmt.setString(6, message);
                stmt.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
